package com.etown.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;
/**
 * 基本的Action类
 * 注意：BaseAction封装了获取request、response、session的快捷方式
 * 以及通用的写响应工具
 * 所有action包中的所有类都继承BaseAction
 * @author: ZhangZhun Date：2011-4-1 上午09:48:47
 */
public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware,ServletContextAware{
	private static final long serialVersionUID = 1L;
	protected final Log log=LogFactory.getLog(this.getClass());
	
	private int start;
	private int limit;
	private String sort;
	private String dir;
	
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected ServletContext servletContext;
	
	public void setServletRequest(HttpServletRequest request) {
		this.request=request;
	}
	public void setServletResponse(HttpServletResponse response) {
		this.response=response;		
	}
	protected HttpSession getSession(){
		return this.request.getSession();
	}
	
	/**
	 * 设置Session级属性
	 * @param key
	 * @param obj
	 */
	protected void setSessionAttr(String key,Object obj){
		this.getSession().setAttribute(key, obj);
	}
	
	protected Object getSessionAttr(String key){
		return this.getSession().getAttribute(key);
	}
	
	/**
	 * 删除Session级属性
	 * @param key
	 */
	protected void rmSessionAttr(String key){
		this.getSession().removeAttribute(key);
	}
	
	/**
	 * 设置Request级属性
	 * @param key
	 * @param obj
	 */
	protected void setReqAttr(String key,Object obj){
		this.request.setAttribute(key, obj);
	}
	
	protected Object getReqAttr(String key){
		return this.request.getAttribute(key);
	}
	
	/**
	 * 删除Request级属性
	 * @param key
	 */
	protected void rmReqAttr(String key){
		this.request.removeAttribute(key);
	}
	
	public void setServletContext(ServletContext context) {
		this.servletContext=context;
	}
	/**
	 * 输出文件流
	 * @author: ZhangZhun
	 * Date：2011-4-2 上午11:19:59
	 * @param is
	 * @param fileName
	 * @param contentType
	 * @param len
	 * @throws IOException
	 */
	public void outFileStream(InputStream is,String fileName,String contentType,int len) throws IOException{
//		response.setCharacterEncoding("UTF-8");
//		response.setContentType("application/octet-stream;charset=UTF-8");
//		if(len>0)
//			response.setContentLength(len);
//		if(StringUtils.isNotEmpty(fileName)){
//			response.setHeader("Content-Disposition", "attachment;filename="
//					+ new String(fileName.getBytes(),"ISO-8859-1"));
//		}
//		if(StringUtils.isNotEmpty(contentType)){
//			response.setHeader("Content-Type", contentType);
//		}
//		StreamOperatorUtil.fromCopyTo(is, response.getOutputStream());
	}
	/**
	 * 输出一个对象
	 * @author: ZhangZhun
	 * Date：2011-4-1 上午10:12:04
	 * @param o
	 * @param isInjectDefaultConvertHandler 是否注入默认对象转换类
	 */
	public void outJsonObject(Object o,boolean isInjectDefaultConvertHandler){
		if(Collection.class.isInstance(o)||o.getClass().isArray()){
			JSONArray ja=null;
			if(isInjectDefaultConvertHandler){
				ja=JSONArray.fromObject(o,getJsonConfig(null));
			}else{
				ja=JSONArray.fromObject(o);
			}
			this.outJsonString(ja.toString());
		}else{
			JSONObject jo=null;
			if(isInjectDefaultConvertHandler){
				jo=JSONObject.fromObject(o,getJsonConfig(null));
			}else{
				jo=JSONObject.fromObject(o);
			}
			this.outJsonString(jo.toString());
		}
	}
	/**
	 * 根据指定格式格式化日期
	 * @author: ZhangZhun
	 * Date：2011-4-1 上午09:55:42
	 * @param format
	 * @return
	 */
	public JsonConfig getJsonConfig(String format) {
//		if(format == null) {
//			format=WEB_PROPERTIES.getProperty("DEFAULT_JSON_DATE_FORMAT",Constants.DATETIME_FORMAT);
//		}
//		JsonConfig conf = new JsonConfig();
//		conf.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);   
//		conf.registerJsonValueProcessor(Date.class,new JsonValueProcessorImpl(format));
//		conf.registerJsonValueProcessor(Timestamp.class,new JsonValueProcessorImpl(format));
//		return conf;
		return null;
	}
	/**
	 * 输出简单消息
	 * @author: ZhangZhun
	 * Date：2011-4-1 下午05:42:41
	 * @param success
	 * @param message
	 */
	public void outSimpleMessage(boolean success,String message){
		JSONObject jo=new JSONObject();
		jo.accumulate("success", success);
		jo.accumulate("message", message);
		this.outJsonString(jo.toString());
	}
	/**
	 * 输出结果消息
	 * @author: ZhangZhun
	 * Date：2011-4-1 下午05:45:12
	 * @param success
	 * @param message
	 * @param isInjectDefaultConvertHandler 是否注入默认对象转换类
	 */
	public void outResultMessage(Object result,String message,boolean isInjectDefaultConvertHandler){
		JSONObject jo=new JSONObject();
		Object o=null;
		if(Collection.class.isInstance(result)||result.getClass().isArray()){
			if(isInjectDefaultConvertHandler){
				o=JSONArray.fromObject(result, this.getJsonConfig(null));
			}else{
				o=JSONArray.fromObject(result, this.getJsonConfig(null));
			}
		}else{
			if(isInjectDefaultConvertHandler){
				o=JSONObject.fromObject(result,this.getJsonConfig(null));
			}else{
				o=JSONObject.fromObject(result);
			}
		}
		jo.accumulate("success", true);
		jo.accumulate("item", o);
		jo.accumulate("message", message);
		this.outJsonString(jo.toString());
	}
	/**
	 * 输出JSON字符串，根据指定的字符集
	 * @author: ZhangZhun
	 * Date：2011-4-1 上午09:22:17
	 * @param str
	 * @param charset
	 */
	public void outJsonString(String str,String charset){
		this.response.setContentType("text/html;charset="+charset);
		this.responseJsonString(str);
	}
	/**
	 * 输出JSON字符串，根据默认的字符集
	 * @author: ZhangZhun
	 * Date：2011-4-1 上午09:23:25
	 * @param str
	 */
	public void outJsonString(String str){
		outJsonString(str,"UTF-8");
		//outJsonString(str,WEB_PROPERTIES.getProperty("DEFAULT_JSON_CHARSET","UTF-8"));
	}
	/**
	 * 输入JSON字符串
	 * @author: ZhangZhun
	 * Date：2011-4-1 上午09:47:28
	 * @param str
	 */
	private void responseJsonString(String str) {
		try {
			this.response.setHeader("Cache-Control","no-cache");
			this.response.setHeader("Cache-Control","no-store");
			this.response.setDateHeader("Expires", 0L);
			this.response.setHeader("Pragma", "no-cache");			
			PrintWriter out = this.response.getWriter();
			out.write(str);
			out.flush();
			this.response.flushBuffer();
		} catch (IOException e) {
			log.error("向响应中写数据失败");
		}
	}
	
	/**
	 * 获取文件名和后缀名部分
	 * @author: ZhangZhun
	 * Date：2011-4-7 下午04:04:15
	 * @param filePath
	 * @return
	 */
	public String getFileNameByPath(String filePath){
		int separtorPos=filePath.indexOf("\\");
		if(separtorPos==-1){
			separtorPos=filePath.indexOf("/");
		}
		if(separtorPos!=-1){
			return filePath.substring(separtorPos,filePath.length());
		}
		return filePath;
	}
	/**
	 * 获取文件后缀名
	 * @author: ZhangZhun
	 * Date：2011-4-7 下午04:05:49
	 * @param filePath
	 * @return
	 */
	public String getFileNameSuffix(String filePath){
		int suffixPos=filePath.lastIndexOf('.');
		if(suffixPos!=-1){
			return filePath.substring(suffixPos);
		}
		return filePath;
	}
	
	/**
	 * 获取客户端的真实IP地址
	 * @return
	 */
	public String getIpAddr() {
	       String ip = request.getHeader("x-forwarded-for");
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("WL-Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getRemoteAddr();
	       }
	       return ip;
	   }
	
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getLimit() {
		return limit;
	}
	public void setLimit(int limit) {
		this.limit = limit;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getDir() {
		return dir;
	}
	public void setDir(String dir) {
		this.dir = dir;
	}
}
